<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useProductsStore } from '../stores/products'
import { useCartStore } from '../stores/cart'
import { useUserStore } from '../stores/user'

const route = useRoute()
const router = useRouter()
const productsStore = useProductsStore()
const cartStore = useCartStore()
const userStore = useUserStore()

// 获取商品ID
const productId = route.params.id

// 商品详情
const product = ref(null)
const isLoading = ref(false)

// 异步获取商品详情
const fetchProductDetail = async () => {
  isLoading.value = true
  try {
    console.log('正在获取商品详情，ID:', productId)
    const data = await productsStore.getProductById(productId)
    if (data) {
      product.value = data
      console.log('成功获取商品详情:', data.name)
    } else {
      // 商品不存在，设置错误状态但不立即重定向，让用户有时间看到提示
      console.warn('未找到商品，ID:', productId)
      // 这里可以添加一个错误提示，而不是直接重定向
      // 保留商品不存在的状态，让用户有机会返回或重试
      product.value = null
    }
  } catch (err) {
    console.error('获取商品详情失败:', err)
    // 记录错误但不立即重定向
    product.value = null
  } finally {
    isLoading.value = false
  }
}

// 规格选择
const selectedSpec = ref('')
const quantity = ref(1)

// 切换图片索引
const currentImageIndex = ref(0)

// 计算商品图片数组
const productImages = computed(() => {
  if (!product.value) return []
  
  const images = []
  // 添加主图
  if (product.value.image) {
    images.push(product.value.image)
  }
  // 添加额外图片
  if (Array.isArray(product.value.images)) {
    images.push(...product.value.images)
  }
  
  // 如果没有图片，提供默认占位图
  if (images.length === 0) {
    images.push('/default-product.jpg') // 假设有默认图片
  }
  
  return images
})

// 加入购物车相关
const isAddingToCart = ref(false)
const addToCartSuccess = ref(false)

// 评价分页
const reviewPage = ref(1)
const reviewsPerPage = 5

// 计算当前商品的评价
const productReviews = computed(() => {
  if (!product.value || !product.value.reviews) return []
  return product.value.reviews.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
})

// 分页后的评价
const paginatedReviews = computed(() => {
  const start = (reviewPage.value - 1) * reviewsPerPage
  const end = start + reviewsPerPage
  return productReviews.value.slice(start, end)
})

// 评价总页数
const totalReviewPages = computed(() => {
  return Math.ceil(productReviews.value.length / reviewsPerPage)
})

// 相关商品（同分类）
const relatedProducts = computed(() => {
  if (!product.value) return []
  return productsStore.products
    .filter(p => p.id !== productId && p.categoryId === product.value.categoryId)
    .slice(0, 4)
})

// 选择规格
const selectSpec = (spec) => {
  selectedSpec.value = spec
}

// 改变数量
// 获取当前规格和颜色的库存
const getCurrentStock = () => {
  if (!product.value) return null
  
  // 如果没有选中规格，返回整体库存（如果是数字）
  if (!selectedSpec.value && typeof product.value.stock === 'number') {
    return product.value.stock
  }
  
  // 如果是结构化库存（按尺码/颜色）
  if (typeof product.value.stock === 'object' && product.value.stock !== null && selectedSpec.value) {
    try {
      // 解析规格，假设格式为 '尺码,颜色' 或类似格式
      const specParts = selectedSpec.value.split(',')
      let currentStock = product.value.stock
      
      // 直接尝试使用规格值作为键查找库存
      if (currentStock[selectedSpec.value] !== undefined) {
        return currentStock[selectedSpec.value] || 0
      }
      
      // 如果直接查找失败，尝试解析规格部分
      for (const part of specParts) {
        const trimmedPart = part.trim()
        // 尝试匹配键名（大小写不敏感）
        const matchingKey = Object.keys(currentStock).find(key => 
          key.toLowerCase() === trimmedPart.toLowerCase() || 
          key === trimmedPart
        )
        
        if (matchingKey) {
          if (typeof currentStock[matchingKey] === 'object' && currentStock[matchingKey] !== null) {
            currentStock = currentStock[matchingKey]
          } else {
            return currentStock[matchingKey] || 0
          }
        }
      }
      
      // 如果遍历完所有部分后，currentStock仍然是对象，尝试返回默认值
      return typeof currentStock === 'number' ? currentStock : 0
    } catch (error) {
      console.error('获取库存失败:', error)
      return 0
    }
  } else if (typeof product.value.stock === 'number') {
    // 简单数字库存
    return product.value.stock
  }
  
  return 0 // 默认返回0
  }

  const changeQuantity = (delta) => {
    const newQuantity = quantity.value + delta
    const currentStock = getCurrentStock()
    
    if (newQuantity >= 1 && (!currentStock || newQuantity <= currentStock)) {
      quantity.value = newQuantity
    }
  }

// 切换图片
const changeImage = (index) => {
  currentImageIndex.value = index
}

// 加入购物车
const addToCart = async () => {
  if (!selectedSpec.value) {
    alert('请选择商品规格')
    return
  }
  
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }
  
  try {
    isAddingToCart.value = true
    
    const cartItem = {
      productId: product.value.id,
      name: product.value.name,
      image: productImages.length > 0 ? productImages[0] : '/default-product.jpg',
      price: product.value.price,
      spec: selectedSpec.value,
      quantity: quantity.value,
      stock: product.value.stock
    }
    
    await cartStore.addToCart(cartItem)
    
    // 显示成功提示
    addToCartSuccess.value = true
    setTimeout(() => {
      addToCartSuccess.value = false
    }, 3000)
    
  } catch (error) {
    alert('添加失败，请重试')
  } finally {
    isAddingToCart.value = false
  }
}

// 立即购买
const buyNow = async () => {
  if (!selectedSpec.value) {
    alert('请选择商品规格')
    return
  }
  
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }
  
  // 先添加到购物车，然后跳转到结算页
  await addToCart()
  router.push('/cart')
}

// 检查尺码属性是否存在
const hasSizeProperty = (property) => {
  if (!product.value || !product.value.sizeChart) return false
  
  // 检查任何一个尺码信息中是否包含指定属性
  for (const sizeInfo of Object.values(product.value.sizeChart)) {
    if (sizeInfo && sizeInfo[property]) {
      return true
    }
  }
  return false
}

// 加载商品详情和初始化
onMounted(async () => {
  // 获取商品详情
  await fetchProductDetail()
  
  // 初始化选中第一个规格
  if (product.value && product.value.specs) {
    // 处理数组格式的规格
    if (Array.isArray(product.value.specs) && product.value.specs.length > 0) {
      selectedSpec.value = product.value.specs[0]
    }
    // 处理对象格式的规格（包含options数组）
    else if (product.value.specs.options && product.value.specs.options.length > 0) {
      const firstOption = product.value.specs.options[0]
      // 确保获取的是值而不是整个对象
      selectedSpec.value = typeof firstOption === 'string' ? firstOption : firstOption.value
    }
  }
  
  // 加载购物车数据
  if (userStore.isLoggedIn) {
    await cartStore.loadCart()
  }
})
</script>

<template>
  <main class="product-detail-container">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 商品详情内容 -->
    <div v-else-if="product" class="container">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <a href="/" class="breadcrumb-link">首页</a>
        <span class="breadcrumb-separator">/</span>
        <a :href="{ name: 'products', query: { category: product.categoryId } }" class="breadcrumb-link">{{ productsStore.getCategoryName(product.categoryId) }}</a>
        <span class="breadcrumb-separator">/</span>
        <span class="breadcrumb-current">{{ product.name }}</span>
      </div>
      
      <!-- 商品主信息 -->
      <div class="product-main">
        <!-- 商品图片 -->
        <div class="product-images">
          <div class="thumbnail-list">
            <div 
              v-for="(image, index) in productImages"
              :key="index"
              class="thumbnail-item"
              :class="{ active: index === currentImageIndex }"
              @click="changeImage(index)"
            >
              <img :src="image" :alt="product?.name || '商品图片'" class="thumbnail-image" />
            </div>
          </div>
          <div class="main-image-wrapper">
            <img 
              :src="productImages[currentImageIndex]" 
              :alt="product?.name || '商品图片'" 
              class="main-image" 
            />
          </div>
        </div>
        
        <!-- 商品信息 -->
        <div class="product-info">
          <h1 class="product-title">{{ product.name }}</h1>
          
          <div class="product-rating">
            <div class="rating-stars">
              <span v-for="i in 5" :key="i" class="star">⭐</span>
            </div>
            <span class="rating-value">{{ product.rating }}</span>
            <span class="rating-count">({{ product.reviewCount }} 条评价)</span>
            <span class="sales-count">已售 {{ product.sales }}</span>
          </div>
          
          <div class="product-price-section">
            <div class="price-main">
              <span class="current-price">¥{{ product.price }}</span>
              <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
              <span v-if="product.discount" class="discount-badge">{{ product.discount }}</span>
            </div>
          </div>
          
          <!-- 库存显示 -->
          <div class="product-stock">
            <span>
              库存：
              <template v-if="getCurrentStock() !== null">
                {{ getCurrentStock() > 0 ? getCurrentStock() : '无货' }}
              </template>
              <template v-else>
                {{ product.stock || '无限' }}
              </template>
            </span>
          </div>
          
          <!-- 规格选择 -->
          <div class="spec-selection" v-if="product.specs">
            <h3 class="spec-title">选择规格</h3>
            <div v-if="Array.isArray(product.specs) && product.specs.length > 0" class="spec-options">
              <div 
                v-for="spec in product.specs" 
                :key="spec"
                class="spec-option"
                :class="{ 
                  active: spec === selectedSpec,
                  'out-of-stock': getCurrentStock() === 0
                }"
                @click="selectSpec(spec)"
              >
                {{ spec }}
                <span v-if="getCurrentStock() === 0" class="stock-label">无货</span>
              </div>
            </div>
            <div v-else-if="product.specs.options && product.specs.options.length > 0" class="spec-options">
              <div 
                v-for="spec in product.specs.options" 
                :key="spec.value || spec"
                class="spec-option"
                :class="{ 
                  active: (typeof spec === 'string' ? spec : spec.value) === selectedSpec,
                  'out-of-stock': getCurrentStock() === 0
                }"
                @click="selectSpec(typeof spec === 'string' ? spec : spec.value)"
              >
                {{ typeof spec === 'string' ? spec : spec.label }}
                <span v-if="getCurrentStock() === 0" class="stock-label">无货</span>
              </div>
            </div>
          </div>
          
          <!-- 数量选择 -->
          <div class="quantity-section">
            <h3 class="quantity-title">数量</h3>
            <div class="quantity-control">
              <button 
                class="quantity-btn minus" 
                @click="changeQuantity(-1)"
                :disabled="quantity <= 1"
              >
                -
              </button>
              <input 
                type="number" 
                v-model.number="quantity" 
                class="quantity-input"
                :min="1" 
                :max="getCurrentStock() || 99"
              />
              <button 
                class="quantity-btn plus" 
                @click="changeQuantity(1)"
                :disabled="getCurrentStock() && quantity >= getCurrentStock()"
              >
                +
              </button>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button 
              class="add-to-cart-btn" 
              @click="addToCart"
              :disabled="isAddingToCart"
            >
              <span v-if="!isAddingToCart">加入购物车</span>
              <span v-else>添加中...</span>
            </button>
            <button 
              class="buy-now-btn" 
              @click="buyNow"
              :disabled="isAddingToCart"
            >
              立即购买
            </button>
          </div>
          
          <!-- 成功提示 -->
          <div v-if="addToCartSuccess" class="success-message">
            ✓ 已成功加入购物车
          </div>
        </div>
      </div>
      
      <!-- 商品详情和评价 -->
      <div class="product-details-reviews">
        <!-- 选项卡导航 -->
        <div class="tab-navigation">
          <button class="tab-button active">商品详情</button>
          <button class="tab-button">用户评价 ({{ product.reviewCount }})</button>
        </div>
        
        <!-- 商品详情 -->
        <div class="tab-content active">
          <div class="product-description">
            <h2>商品描述</h2>
            <p>{{ product.description }}</p>
          </div>
          
          <!-- 技术规格 -->
          <div v-if="product.technicalSpecs" class="product-technical-specs">
            <h2>技术规格</h2>
            <table class="params-table">
              <tbody>
                <tr v-for="(value, key) in product.technicalSpecs" :key="key">
                  <td class="param-label">{{ key.charAt(0).toUpperCase() + key.slice(1).replace(/([A-Z])/g, ' $1') }}</td>
                  <td class="param-value">{{ value }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 商品参数 -->
      <div class="product-params">
        <h2>商品参数</h2>
        <table class="params-table">
          <tbody>
            <tr>
              <td class="param-label">品牌</td>
              <td class="param-value">{{ product.brand || '暂无' }}</td>
            </tr>
            <tr>
              <td class="param-label">型号</td>
              <td class="param-value">{{ product.model || '暂无' }}</td>
            </tr>
            <tr>
              <td class="param-label">重量</td>
              <td class="param-value">{{ product.weight || '暂无' }}</td>
            </tr>
            <tr>
              <td class="param-label">产地</td>
              <td class="param-value">{{ product.origin || '暂无' }}</td>
            </tr>
            <!-- 尺码信息 -->
            <tr v-if="product.sizeInfo">
              <td class="param-label">尺码信息</td>
              <td class="param-value">
                <div v-if="typeof product.sizeInfo === 'string'">
                  {{ product.sizeInfo }}
                </div>
                <div v-else-if="typeof product.sizeInfo === 'object'">
                  <div v-for="(size, key) in product.sizeInfo" :key="key" class="size-item">
                    {{ key }}: {{ size }}
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 尺码表信息 -->
      <div class="product-params" v-if="product.sizeChart">
        <h2>尺码信息</h2>
        <div class="size-chart-container">
          <table class="params-table">
            <thead>
              <tr>
                <th class="param-label">尺码</th>
                <th v-if="hasSizeProperty('shoulderWidth')" class="param-label">肩宽</th>
                <th v-if="hasSizeProperty('chest')" class="param-label">胸围</th>
                <th v-if="hasSizeProperty('waist')" class="param-label">腰围</th>
                <th v-if="hasSizeProperty('hip')" class="param-label">臀围</th>
                <th v-if="hasSizeProperty('footLength')" class="param-label">脚长</th>
                <th v-if="hasSizeProperty('length')" class="param-label">衣长/裤长</th>
                <th v-if="hasSizeProperty('sleeveLength')" class="param-label">袖长</th>
                <th v-if="hasSizeProperty('thigh')" class="param-label">大腿围</th>
                <th v-if="hasSizeProperty('usSize')" class="param-label">美码</th>
                <th v-if="hasSizeProperty('ukSize')" class="param-label">英码</th>
                <th class="param-label">适用说明</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(sizeInfo, size) in product.sizeChart" :key="size">
                <td class="param-value">{{ size }}</td>
                <td v-if="sizeInfo.shoulderWidth" class="param-value">{{ sizeInfo.shoulderWidth }}</td>
                <td v-if="sizeInfo.chest" class="param-value">{{ sizeInfo.chest }}</td>
                <td v-if="sizeInfo.waist" class="param-value">{{ sizeInfo.waist }}</td>
                <td v-if="sizeInfo.hip" class="param-value">{{ sizeInfo.hip }}</td>
                <td v-if="sizeInfo.footLength" class="param-value">{{ sizeInfo.footLength }}</td>
                <td v-if="sizeInfo.length" class="param-value">{{ sizeInfo.length }}</td>
                <td v-if="sizeInfo.sleeveLength" class="param-value">{{ sizeInfo.sleeveLength }}</td>
                <td v-if="sizeInfo.thigh" class="param-value">{{ sizeInfo.thigh }}</td>
                <td v-if="sizeInfo.usSize" class="param-value">{{ sizeInfo.usSize }}</td>
                <td v-if="sizeInfo.ukSize" class="param-value">{{ sizeInfo.ukSize }}</td>
                <td class="param-value">{{ sizeInfo.description }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
          
          <!-- 配送信息 -->
          <div v-if="product.shipping" class="product-shipping">
            <h2>配送信息</h2>
            <div class="shipping-details">
              <div class="shipping-item">
                <span class="shipping-label">配送方式：</span>
                <span class="shipping-value">{{ product.shipping.shippingMethods.join('、') }}</span>
              </div>
              <div class="shipping-item">
                <span class="shipping-label">预计送达：</span>
                <span class="shipping-value">{{ product.shipping.estimatedDelivery }}</span>
              </div>
              <div class="shipping-item" v-if="product.shipping.freeShipping">
                <span class="shipping-label">运费：</span>
                <span class="shipping-value free-shipping">免运费</span>
              </div>
            </div>
          </div>
          
          <!-- 售后服务 -->
          <div v-if="product.afterSales" class="product-after-sales">
            <h2>售后服务</h2>
            <div class="after-sales-details">
              <div class="after-sales-item">
                <span class="after-sales-label">质保期限：</span>
                <span class="after-sales-value">{{ product.afterSales.warranty }}</span>
              </div>
              <div class="after-sales-item">
                <span class="after-sales-label">退换政策：</span>
                <span class="after-sales-value">{{ product.afterSales.returnPolicy }}</span>
              </div>
              <div class="after-sales-item">
                <span class="after-sales-label">客服时间：</span>
                <span class="after-sales-value">{{ product.afterSales.supportHours }}</span>
              </div>
            </div>
          </div>
          
          <!-- 包装清单 -->
          <div v-if="product.packageContents" class="product-package">
            <h2>包装清单</h2>
            <ul class="package-list">
              <li v-for="(item, index) in product.packageContents" :key="index" class="package-item">
                {{ item }}
              </li>
            </ul>
          </div>
          
          <!-- 使用教程 -->
          <div v-if="product.tutorial" class="product-tutorial">
            <h2>使用教程</h2>
            <div class="tutorial-guide">
              <h3>快速入门</h3>
              <p>{{ product.tutorial.setupGuide }}</p>
            </div>
            <div v-if="product.tutorial.tips && product.tutorial.tips.length > 0" class="tutorial-tips">
              <h3>使用小贴士</h3>
              <ul class="tips-list">
                <li v-for="(tip, index) in product.tutorial.tips" :key="index" class="tip-item">
                  {{ tip }}
                </li>
              </ul>
            </div>
          </div>
        </div>
        
        <!-- 用户评价 -->
        <div class="tab-content">
          <div class="reviews-section">
            <h2>用户评价</h2>
            
            <div class="reviews-list">
              <div 
                v-for="review in paginatedReviews" 
                :key="review.id"
                class="review-item"
              >
                <div class="review-header">
                  <div class="review-user">
                    <span class="user-avatar">{{ review.userName.charAt(0) }}</span>
                    <span class="user-name">{{ review.userName }}</span>
                  </div>
                  <div class="review-rating">
                    <span v-for="i in 5" :key="i" class="star">⭐</span>
                  </div>
                </div>
                <div class="review-content">
                  <p>{{ review.content }}</p>
                </div>
                <div class="review-date">{{ new Date(review.createdAt).toLocaleDateString() }}</div>
              </div>
            </div>
            
            <!-- 评价分页 -->
            <div v-if="totalReviewPages > 1" class="reviews-pagination">
              <button 
                class="pagination-btn"
                :disabled="reviewPage === 1"
                @click="reviewPage--"
              >
                ← 上一页
              </button>
              
              <div class="page-numbers">
                <button
                  v-for="page in totalReviewPages"
                  :key="page"
                  class="page-btn"
                  :class="{ active: page === reviewPage }"
                  @click="reviewPage = page"
                >
                  {{ page }}
                </button>
              </div>
              
              <button 
                class="pagination-btn"
                :disabled="reviewPage === totalReviewPages"
                @click="reviewPage++"
              >
                下一页 →
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 相关商品 -->
      <div v-if="relatedProducts.length > 0" class="related-products">
        <h2 class="section-title">相关商品</h2>
        <div class="products-grid">
          <div v-for="relatedProduct in relatedProducts" :key="relatedProduct.id" class="product-card">
            <a :href="`/products/${relatedProduct.id}`" class="product-link">
              <div class="product-image-wrapper">
                <img :src="relatedProduct.image" :alt="relatedProduct.name" class="product-image" />
              </div>
              <div class="product-info">
                <h3 class="product-name">{{ relatedProduct.name }}</h3>
                <div class="product-price">¥{{ relatedProduct.price }}</div>
              </div>
            </a>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 商品不存在 -->
    <div v-else class="product-not-found">
      <div class="not-found-icon">🔍</div>
      <h2>商品不存在</h2>
      <p>很抱歉，您查找的商品不存在或已下架</p>
      <a href="/products" class="back-home-btn">返回商品列表</a>
      <a href="/" class="back-home-btn" style="margin-left: 10px;">返回首页</a>
    </div>
  </main>
  </template>

<style scoped>
/* 新增商品详情样式 */
.product-technical-specs,
.product-shipping,
.product-after-sales,
.product-package,
.product-tutorial {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.product-technical-specs h2,
.product-shipping h2,
.product-after-sales h2,
.product-package h2,
.product-tutorial h2 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  font-size: 1.4rem;
  font-weight: 600;
  border-bottom: 2px solid #4CAF50;
  padding-bottom: 8px;
}

/* 技术规格表格样式 */
.product-technical-specs .params-table {
  width: 100%;
  border-collapse: collapse;
}

.product-technical-specs .param-label {
  width: 30%;
  padding: 10px 15px;
  background-color: #f2f2f2;
  font-weight: 500;
  color: #666;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.product-technical-specs .param-value {
  padding: 10px 15px;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
}

/* 配送信息样式 */
.shipping-details,
.after-sales-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.shipping-item,
.after-sales-item {
  flex: 1;
  min-width: 200px;
  padding: 10px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.shipping-label,
.after-sales-label {
  display: inline-block;
  margin-right: 5px;
  color: #666;
  font-weight: 500;
}

.shipping-value,
.after-sales-value {
  color: #333;
}

.free-shipping {
  color: #4CAF50;
  font-weight: 600;
}

/* 包装清单样式 */
.package-list {
  padding-left: 20px;
}

.package-item {
  margin-bottom: 8px;
  padding: 8px 12px;
  background-color: white;
  border-radius: 4px;
  color: #333;
  position: relative;
  padding-left: 20px;
}

.package-item:before {
  content: '✓';
  position: absolute;
  left: 5px;
  color: #4CAF50;
  font-weight: bold;
}

/* 使用教程样式 */
.tutorial-guide,
.tutorial-tips {
  margin-bottom: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.tutorial-guide h3,
.tutorial-tips h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #4CAF50;
  font-size: 1.1rem;
}

.tutorial-guide p {
  color: #333;
  line-height: 1.6;
  margin: 0;
}

.tips-list {
  padding-left: 20px;
  margin: 0;
}

.tip-item {
  margin-bottom: 8px;
  color: #333;
  line-height: 1.5;
  position: relative;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shipping-details,
  .after-sales-details {
    flex-direction: column;
  }
  
  .shipping-item,
  .after-sales-item {
    min-width: auto;
  }
  
  .product-technical-specs .param-label {
    width: 40%;
    font-size: 0.9rem;
  }
}

/* 无货状态样式 */
.product-stock {
  color: #666;
  font-size: 0.95rem;
  margin-bottom: 15px;
}

.product-stock span:last-child {
  color: #4CAF50;
  font-weight: 500;
}
</style>

<style scoped>
.product-detail-container {
  min-height: calc(100vh - 130px);
  padding: 20px 0;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  gap: 20px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误页面样式 */
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
  padding: 40px 20px;
}

.error-content {
  text-align: center;
  max-width: 500px;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.error-content h2 {
  color: #e74c3c;
  margin-bottom: 16px;
  font-size: 28px;
}

.error-content p {
  color: #555;
  margin-bottom: 32px;
  font-size: 16px;
  line-height: 1.6;
}

.error-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.btn-primary {
  background-color: #3498db;
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  text-decoration: none;
  font-weight: 500;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  text-decoration: none;
  font-weight: 500;
  transition: background-color 0.3s;
}

.btn-secondary:hover {
  background-color: #7f8c8d;
}

/* 面包屑导航 */
.breadcrumb {
  margin-bottom: 30px;
  font-size: 14px;
  color: #6c757d;
  padding: 20px 0 0;
}

.breadcrumb-link {
  color: #6c757d;
  text-decoration: none;
}

.breadcrumb-link:hover {
  color: #495057;
  text-decoration: underline;
}

.breadcrumb-separator {
  margin: 0 10px;
  color: #dee2e6;
}

.breadcrumb-current {
  color: #212529;
  font-weight: 500;
}

/* 商品主信息 */
.product-main {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 60px;
  margin-bottom: 0;
  padding: 40px 0;
  background-color: #ffffff;
}

/* 商品图片 */
.product-images {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.thumbnail-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex-shrink: 0;
}

.thumbnail-item {
  width: 90px;
  height: 90px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #ffffff;
}

.thumbnail-item:hover,
.thumbnail-item.active {
  border-color: #adb5bd;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.main-image-wrapper {
  flex: 1;
  min-height: 500px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
}

.main-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}

.main-image-wrapper:hover .main-image {
  transform: scale(1.05);
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.thumbnail-item.active .thumbnail-image {
  transform: scale(1.1);
  border-color: #6c757d;
}

.main-image-wrapper:hover .main-image {
  transform: scale(1.02);
}

/* 商品信息 */
.product-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 10px 0;
}

.product-title {
  font-size: 32px;
  font-weight: 600;
  color: #212529;
  line-height: 1.3;
  margin-bottom: 10px;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 15px;
  background-color: #f8f9fa;
  padding: 12px 16px;
  border-radius: 6px;
  border-bottom: none;
  padding: 12px 16px;
  margin-bottom: 10px;
}

.rating-stars {
  display: flex;
  gap: 3px;
}

.star {
  color: #ffb400;
  font-size: 16px;
}

.rating-value {
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.rating-count {
  color: #6c757d;
}

.sales-count {
  color: #6c757d;
  margin-left: auto;
  font-weight: 500;
}

.product-price-section {
  padding: 24px;
  background-color: #ffffff;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  border-bottom: none;
  margin-bottom: 10px;
}

.price-main {
  display: flex;
  align-items: center;
  gap: 15px;
}

.current-price {
  font-size: 36px;
  font-weight: 600;
  color: #212529;
}

.original-price {
  font-size: 18px;
  color: #adb5bd;
  text-decoration: line-through;
}

.discount-badge {
  background-color: #f8f9fa;
  color: #6c757d;
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  border: 1px solid #e9ecef;
}

.product-stock {
  font-size: 16px;
  color: #6c757d;
  padding: 10px 0;
}

/* 规格选择 */
.spec-selection {
  padding: 15px 0;
  border-bottom: 1px solid #e9ecef;
}

.spec-title {
  font-size: 16px;
  font-weight: 600;
  color: #212529;
  margin-bottom: 12px;
}

.spec-options {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.spec-option {
  padding: 12px 24px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #ffffff;
  color: #495057;
  font-weight: 500;
  position: relative;
}

.spec-option:hover:not(.out-of-stock) {
  border-color: #adb5bd;
  background-color: #f8f9fa;
}

.spec-option.active {
  border-color: #6c757d;
  background-color: #f8f9fa;
  color: #212529;
  font-weight: 600;
}

.spec-option.out-of-stock {
  border-color: #e9ecef;
  background-color: #f8f9fa;
  color: #adb5bd;
  cursor: not-allowed;
}

.spec-option.out-of-stock .stock-label {
  font-size: 12px;
  margin-left: 8px;
  color: #dc3545;
  font-weight: 500;
}

/* 数量选择 */
.quantity-section {
  padding: 15px 0;
  border-bottom: 1px solid #e9ecef;
}

.quantity-title {
  font-size: 16px;
  font-weight: 600;
  color: #212529;
  margin-bottom: 12px;
}

.quantity-control {
  display: flex;
  align-items: center;
  width: fit-content;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  overflow: hidden;
  background-color: #ffffff;
}

.quantity-btn {
  width: 45px;
  height: 45px;
  border: none;
  background-color: #f8f9fa;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #495057;
}

.quantity-btn:hover:not(:disabled) {
  background-color: #e9ecef;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background-color: #f8f9fa;
}

.quantity-btn.minus {
  border-radius: 6px 0 0 6px;
}

.quantity-btn.plus {
  border-radius: 0 6px 6px 0;
}

.quantity-input {
  width: 65px;
  height: 45px;
  border: none;
  border-left: 1px solid #dee2e6;
  border-right: 1px solid #dee2e6;
  text-align: center;
  font-size: 16px;
  color: #212529;
  background-color: #ffffff;
}

.quantity-input:focus {
  outline: none;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 30px;
}

.add-to-cart-btn,
.buy-now-btn {
  flex: 1;
  height: 50px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.add-to-cart-btn {
  background-color: #ffffff;
  color: #6c757d;
  border: 1px solid #dee2e6;
}

.add-to-cart-btn:hover:not(:disabled) {
  background-color: #f8f9fa;
  border-color: #adb5bd;
}

.buy-now-btn {
  background-color: #212529;
  color: #ffffff;
}

.buy-now-btn:hover:not(:disabled) {
  background-color: #343a40;
}

.add-to-cart-btn:disabled,
.buy-now-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.success-message {
  background-color: #f8f9fa;
  color: #212529;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-weight: 600;
  animation: fadeIn 0.3s ease;
  border: 1px solid #dee2e6;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 商品详情和评价 */
.product-details-reviews {
  background-color: #ffffff;
  border-radius: 0;
  overflow: hidden;
  margin-bottom: 0;
  border-top: 1px solid #e9ecef;
}

.tab-navigation {
  display: flex;
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  justify-content: center;
}

.tab-button {
  flex: 1;
  padding: 20px;
  border: none;
  background: none;
  font-size: 16px;
  font-weight: 600;
  color: #6c757d;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  max-width: 200px;
}

.tab-button:hover {
  color: #212529;
  background-color: #e9ecef;
}

.tab-button.active {
  color: #212529;
  background-color: #ffffff;
}

.tab-button.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  background-color: #212529;
}

.tab-content {
  padding: 40px;
  display: none;
}

.tab-content.active {
  display: block;
}

.product-description h2,
.product-params h2,
.reviews-section h2 {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 20px;
}

.product-description p {
  font-size: 16px;
  line-height: 1.8;
  color: #666;
  margin-bottom: 30px;
}

.params-table {
  width: 100%;
  border-collapse: collapse;
}

.params-table tr {
  border-bottom: 1px solid #f0f0f0;
}

.params-table td {
  padding: 15px 0;
  font-size: 16px;
}

.param-label {
  width: 120px;
  font-weight: 500;
  color: #333;
}

.param-value {
  color: #666;
  line-height: 1.6;
}

.size-item {
  margin-bottom: 8px;
  padding: 4px 0;
  font-size: 15px;
  color: #495057;
}

.size-item:last-child {
  margin-bottom: 0;
}

/* 尺码表样式 */
.size-chart-container {
  margin-bottom: 30px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.size-chart-container .params-table {
  background-color: #ffffff;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  overflow: hidden;
  min-width: 600px;
}

.size-chart-container .params-table thead {
  background-color: #f8f9fa;
}

.size-chart-container .params-table th {
  padding: 15px 20px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  text-align: left;
  border-bottom: 2px solid #dee2e6;
  min-width: 80px;
}

.size-chart-container .params-table td {
  padding: 12px 20px;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #f0f0f0;
  min-width: 80px;
}

.size-chart-container .params-table tbody tr:hover {
  background-color: #f8f9fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .size-chart-container {
    margin-left: -20px;
    margin-right: -20px;
    padding-left: 20px;
    padding-right: 20px;
  }
}

/* 技术规格表格美化 */
.product-technical-specs .params-table {
  background-color: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
}

.product-technical-specs .params-table td {
  padding: 15px 20px;
}

.product-technical-specs .param-label {
  background-color: #e9ecef;
  font-weight: 600;
}

/* 评价列表 */
.reviews-list {
  display: flex;
  flex-direction: column;
  gap: 30px;
  margin-bottom: 30px;
}

.review-item {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.review-user {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #4285f4;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.user-name {
  font-weight: 500;
  color: #333;
}

.review-content p {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 10px;
}

.review-date {
  font-size: 14px;
  color: #999;
}

/* 评价分页 */
.reviews-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

/* 相关商品 */
.related-products {
  margin-bottom: 40px;
}

.section-title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 24px;
  text-align: center;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.product-card {
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.product-link {
  text-decoration: none;
  display: block;
}

.product-image-wrapper {
  height: 280px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-info {
  padding: 16px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  font-size: 20px;
  font-weight: 700;
  color: #ff4757;
}

/* 商品不存在 */
.product-not-found {
  text-align: center;
  padding: 80px 20px;
  background-color: #fff;
  border-radius: 12px;
  margin: 40px auto;
  max-width: 600px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.not-found-icon {
  font-size: 80px;
  margin-bottom: 24px;
}

.product-not-found h2 {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin-bottom: 12px;
}

.product-not-found p {
  font-size: 16px;
  color: #666;
  margin-bottom: 30px;
}

.back-home-btn {
  display: inline-block;
  padding: 12px 28px;
  background-color: #4285f4;
  color: #fff;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  text-decoration: none;
  transition: background-color 0.3s ease;
}

.back-home-btn:hover {
  background-color: #3367d6;
}

/* 响应式设计 */
@media (max-width: 1440px) {
  .container {
    max-width: 1200px;
  }
  
  .product-main {
    gap: 40px;
  }
}

@media (max-width: 1280px) {
  .container {
    max-width: 1100px;
  }
  
  .product-main {
    gap: 30px;
  }
  
  .main-image-wrapper {
    min-height: 450px;
  }
}

@media (max-width: 1024px) {
  .product-main {
    grid-template-columns: 1fr;
    padding: 30px 0;
  }
  
  .product-images {
    flex-direction: column;
    align-items: center;
  }
  
  .thumbnail-list {
    flex-direction: row;
    overflow-x: auto;
    margin-bottom: 20px;
    width: 100%;
    justify-content: center;
  }
  
  .thumbnail-item {
    flex-shrink: 0;
    width: 80px;
    height: 80px;
  }
  
  .main-image-wrapper {
    min-height: 400px;
    width: 100%;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .breadcrumb {
    padding: 15px 0 0;
    font-size: 13px;
  }
  
  .product-main {
    padding: 20px 0;
  }
  
  .product-title {
    font-size: 26px;
  }
  
  .current-price {
    font-size: 32px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }
  
  .tab-content {
    padding: 24px 15px;
  }
  
  .tab-button {
    padding: 18px 20px;
    font-size: 15px;
  }
  
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    padding: 0 15px;
  }
  
  .section-title {
    font-size: 24px;
    padding: 0 15px;
  }
  
  .product-image-wrapper {
    height: 200px;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 0 15px;
  }
  
  .breadcrumb {
    font-size: 12px;
  }
  
  .product-title {
    font-size: 22px;
  }
  
  .main-image-wrapper {
    min-height: 300px;
  }
  
  .tab-button {
    padding: 15px;
    font-size: 15px;
  }
  
  .tab-content {
    padding: 20px 15px;
  }
  
  .products-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .product-image-wrapper {
    height: 240px;
  }
  
  .product-not-found {
    padding: 60px 15px;
    margin: 40px 15px;
  }
  
  .product-not-found h2 {
    font-size: 24px;
  }
}
</style>